<?php
if (!defined('FosfoaSystem')) {
    exit(1);
}
import($GLOBALS['spConfig']['controller_path'] . '/general.php');
/**
 * PAYPAL支付控制器
 * @author Fosf
 * @version 1.0
 * @created 2011-04-11
 */

class qq extends general
{

    var $APPID = QQ_APPID;
    var $APPKEY = QQ_APPKEY;
    var $CALLBACK;
    var $SCOPE;
    var $debug = 0;
    function __construct()
    {
        parent::__construct();
        $this->CALLBACK = "http://" . $_SERVER["HTTP_HOST"] . spUrl('qq', 'callback');
        $this->SCOPE = array(
            'get_info'=>'1',
            'get_user_info' => '1',
            'add_share' => '1',
            );
        $this->debug=0;
    }

    function login()
    {
        $APPID = $this->APPID;
        $APPKEY = $this->APPKEY;
        $SCOPE = $this->SCOPE;
        $debug = $this->debug;
        /*
        *
        * 参考：http://wiki.open.qq.com/wiki/%E3%80%90QQ%E7%99%BB%E5%BD%95%E3%80%91%E4%BD%BF%E7%94%A8Authorization_Code%E8%8E%B7%E5%8F%96Access_Token
        */
        $sState = md5(date("YmdHis" . getip()));
        $_SESSION["state"] = $sState;
        $aScope = array();
        foreach ($SCOPE as $key => $val) {
            if ($val == 1) {
                $aScope[] = $key;
            }
        }
        $sUri = "http://" . $_SERVER["HTTP_HOST"] . spUrl('qq', 'callback');
        $_SESSION["URI"] = $sUri;
        $aParam = array(
            "response_type" => "code",
            "client_id" => $APPID,
            "redirect_uri" => $sUri,
            "scope" => join(",", $aScope),
            //"state"            =>    $sState
            );
        $aGet = array();
        foreach ($aParam as $key => $val) {
            $aGet[] = $key . "=" . urlencode($val);
        }
        $sUrl = "https://graph.qq.com/oauth2.0/authorize?";
        $sUrl .= join("&", $aGet);
        header("location:" . $sUrl);
    }

    function callback()
    {
        $code = $this->spArgs('code');
        $state = $this->spArgs('state');
        
        $APPID = $this->APPID;
        $APPKEY = $this->APPKEY;
        $SCOPE = $this->SCOPE;
        $debug = $this->debug;
        //if(!isset($_GET["state"])||empty($_GET["state"])||!isset($_GET["code"])||empty($_GET["code"])){
        //    echo "QQ第一步获取参数失败。<br />";
        //}else{
        //	if($_GET["state"]!=$_SESSION["state"]){
        //		echo "网站获取用于第三方应用防止CSRF攻击失败。<br />";
        //		exit;
        //	}
        $sUrl = "https://graph.qq.com/oauth2.0/token";
        $aGetParam = array(
            "grant_type" => "authorization_code",
            "client_id" => $APPID,
            "client_secret" => $APPKEY,
            "code" => $code,
            "state" => $state,
            "redirect_uri" => $_SESSION["URI"]);
        unset($_SESSION["state"]);
        unset($_SESSION["URI"]);


        $sContent = $this->get($sUrl, $aGetParam);
        //echo $sContent;
        if ($sContent !== false) {
            $aTemp = explode("&", $sContent);
            $aParam = array();
            foreach ($aTemp as $val) {
                $aTemp2 = explode("=", $val);
                $aParam[$aTemp2[0]] = $aTemp2[1];
            }
            $_SESSION["access_token"] = $aParam["access_token"];
            $sUrl = "https://graph.qq.com/oauth2.0/me";
            $aGetParam = array("access_token" => $aParam["access_token"]);
            $sContent = $this->get($sUrl, $aGetParam);
            if ($sContent !== false) {
                $aTemp = array();
                preg_match('/callback\(\s+(.*?)\s+\)/i', $sContent, $aTemp);
                $aResult = json_decode($aTemp[1], true);
                
                $_SESSION["openid"] = $aResult["openid"];
                //$this->get_info();
                //dump($aResult);exit;
                if (intval($debug) == 1) {
                    echo "<tr><td class='narrow-label'></td><td><input type='button' onclick='location.href=\"../index.php\";' class='button' value='点此返回首页' /></td></tr>";
                } else {
                   $this->jump(spUrl('qq','get_info')); 
                   //$this->jump(spUrl('main','index'));
                }
            }
        }
    }
    /**
     * 获取用户信息
     */
    function get_info()
    {
        $APPID = $this->APPID;
        
        $sUrl = "https://graph.qq.com/user/get_info";
        $aGetParam = array(
            "access_token" => $_SESSION["access_token"],
            "oauth_consumer_key"    =>    $APPID,
            "openid"                =>    $_SESSION["openid"],
            "format"                =>    "json"
        );
        $sContent = $this->get($sUrl,$aGetParam);
        if($sContent!==FALSE){
            $aResult = json_decode($sContent,true);
            dump($aResult);
            if($aResult["ret"]==0){
                echo "<tr><td class='narrow-label'>用户昵称:</td><td>".$aResult["data"]["nick"]."</td></tr>";
                echo "<tr><td class='narrow-label'>小等头像:</td><td><img src='".$aResult["data"]["head"]."/100' border='0' /></td></tr>";
                echo "<tr><td class='narrow-label'>中等头像:</td><td><img src='".$aResult["data"]["head"]."/50' border='0' /></td></tr>";
                echo "<tr><td class='narrow-label'>大等头像:</td><td><img src='".$aResult["data"]["head"]."/30' border='0' /></td></tr>";
                echo "<tr><td class='narrow-label'>用户性别:</td><td>".($aResult["data"]["sex"]?"男":"女")."</td></tr>";
                echo "<tr><td class='narrow-label'>认证用户:</td><td>".($aResult["data"]["isvip"]?"是":"否")."</td></tr>";
                echo "<tr><td class='narrow-label'>用户邮件:</td><td>".$aResult["data"]["email"]."</td></tr>";
                echo "<tr><td class='narrow-label'>听众个数:</td><td>".$aResult["data"]["fansnum"]."</td></tr>";
                echo "<tr><td class='narrow-label'>接听个数:</td><td>".$aResult["data"]["idolnum"]."</td></tr>";
                echo "<tr><td class='narrow-label'>个人简介:</td><td>".$aResult["data"]["introduction"]."</td></tr>";
                echo "<tr><td class='narrow-label'>企业机构:</td><td>".($aResult["data"]["isent"]?"是":"否")."</td></tr>";
                echo "<tr><td class='narrow-label'>用户帐号:</td><td>".$aResult["data"]["name"]."</td></tr>";
                echo "<tr><td class='narrow-label'>微博个数:</td><td>".$aResult["data"]["tweetnum"]."</td></tr>";
                echo "<tr><td class='narrow-label'>认证信息:</td><td>".$aResult["data"]["verifyinfo"]."</td></tr>";
                echo "<tr><td class='narrow-label'>用户OPENID:</td><td>".$aResult["data"]["openid"]."</td></tr>";
            }else{
                echo "<tr><td class='narrow-label'>反馈消息:</td><td>".$aResult["msg"]."</td></tr>";
            }
        }else{
            echo "<tr><td class='narrow-label'>反馈消息:</td><td>获取用户信息失败。</td></tr>";
        }
    }
    /**
     * 
     */
    function get_user_info()
    {
        $APPID = $this->APPID;
        $sUrl = "https://graph.qq.com/user/get_user_info";
        $aGetParam = array(
            "access_token" => $_SESSION["access_token"],
            "oauth_consumer_key"    =>    $APPID,
            "openid"                =>    $_SESSION["openid"],
            "format"                =>    "json"
        );
        $sContent = $this->get($sUrl,$aGetParam);
        if($sContent!==FALSE){
            $aResult = json_decode($sContent,true);
            dump($aResult);
            if($aResult["ret"]==0){
                echo "<tr><td class='narrow-label'>用户昵称:</td><td>".$aResult["nickname"]."</td></tr>";
                echo "<tr><td class='narrow-label'>小等头像:</td><td><img src='".$aResult["figureurl"]."' border='0' /></td></tr>";
                echo "<tr><td class='narrow-label'>中等头像:</td><td><img src='".$aResult["figureurl_1"]."' border='0' /></td></tr>";
                echo "<tr><td class='narrow-label'>大等头像:</td><td><img src='".$aResult["figureurl_2"]."' border='0' /></td></tr>";
                echo "<tr><td class='narrow-label'>用户性别:</td><td>".$aResult["gender"]."</td></tr>";
                echo "<tr><td class='narrow-label'>用户黄钻:</td><td>".$aResult["vip"]."</td></tr>";
                echo "<tr><td class='narrow-label'>黄钻等级:</td><td>".$aResult["level"]."</td></tr>";
            }else{
                echo "<tr><td class='narrow-label'>反馈消息:</td><td>".$aResult["msg"]."</td></tr>";
            }
        }else{
            echo "<tr><td class='narrow-label'>反馈消息:</td><td>获取用户信息失败。</td></tr>";
        }
    }
    /**
    * GET请求
    */
    function get($sUrl, $aGetParam)
    {
        $debug = $this->debug;
        $oCurl = curl_init();
        if (stripos($sUrl, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $aGet = array();
        foreach ($aGetParam as $key => $val) {
            $aGet[] = $key . "=" . urlencode($val);
        }
        curl_setopt($oCurl, CURLOPT_URL, $sUrl . "?" . join("&", $aGet));
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($debug) === 1) {
            echo "<tr><td class='narrow-label'>请求地址:</td><td><pre>" . $sUrl .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>GET参数:</td><td><pre>" . var_export($aGetParam, true) .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>请求信息:</td><td><pre>" . var_export($aStatus, true) .
                "</pre></td></tr>";
            if (intval($aStatus["http_code"]) == 200) {
                echo "<tr><td class='narrow-label'>返回结果:</td><td><pre>" . $sContent .
                    "</pre></td></tr>";
                if ((@$aResult = json_decode($sContent, true))) {
                    echo "<tr><td class='narrow-label'>结果集合解析:</td><td><pre>" . var_export($aResult, true) .
                        "</pre></td></tr>";
                }
            }
        }
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            echo "<tr><td class='narrow-label'>返回出错:</td><td><pre>" . $aStatus["http_code"] .
                ",请检查参数或者确实是腾讯服务器出错咯。</pre></td></tr>";
            return false;
        }
    }

    /*
    * POST 请求
    */
    function post($sUrl, $aPOSTParam)
    {
        $debug = $this->debug;
        $oCurl = curl_init();
        if (stripos($sUrl, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $aPOST = array();
        foreach ($aPOSTParam as $key => $val) {
            $aPOST[] = $key . "=" . urlencode($val);
        }
        curl_setopt($oCurl, CURLOPT_URL, $sUrl);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, join("&", $aPOST));
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($debug) === 1) {
            echo "<tr><td class='narrow-label'>请求地址:</td><td><pre>" . $sUrl .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>POST参数:</td><td><pre>" . var_export($aPOSTParam, true) .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>请求信息:</td><td><pre>" . var_export($aStatus, true) .
                "</pre></td></tr>";
            if (intval($aStatus["http_code"]) == 200) {
                echo "<tr><td class='narrow-label'>返回结果:</td><td><pre>" . $sContent .
                    "</pre></td></tr>";
                if ((@$aResult = json_decode($sContent, true))) {
                    echo "<tr><td class='narrow-label'>结果集合解析:</td><td><pre>" . var_export($aResult, true) .
                        "</pre></td></tr>";
                }
            }
        }
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            echo "<tr><td class='narrow-label'>返回出错:</td><td><pre>" . $aStatus["http_code"] .
                ",请检查参数或者确实是腾讯服务器出错咯。</pre></td></tr>";
            return false;
        }
    }

    /*
    * 上传图片
    */
    function upload($sUrl, $aPOSTParam, $aFileParam)
    {
        //防止请求超时
        global $aConfig;
        set_time_limit(0);
        $oCurl = curl_init();
        if (stripos($sUrl, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $aPOSTField = array();
        foreach ($aPOSTParam as $key => $val) {
            if (preg_match("/^@/i", $val) > 0) {
                $aPOSTField[$key] = " " . $val;
            } else {
                $aPOSTField[$key] = $val;
            }
        }
        foreach ($aFileParam as $key => $val) {
            $aPOSTField[$key] = "@" . $val; //此处对应的是文件的绝对地址
        }
        curl_setopt($oCurl, CURLOPT_URL, $sUrl);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $aPOSTField);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($debug) === 1) {
            echo "<tr><td class='narrow-label'>请求地址:</td><td><pre>" . $sUrl .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>POST参数:</td><td><pre>" . var_export($aPOSTParam, true) .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>文件参数:</td><td><pre>" . var_export($aFileParam, true) .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>请求信息:</td><td><pre>" . var_export($aStatus, true) .
                "</pre></td></tr>";
            if (intval($aStatus["http_code"]) == 200) {
                echo "<tr><td class='narrow-label'>返回结果:</td><td><pre>" . $sContent .
                    "</pre></td></tr>";
                if ((@$aResult = json_decode($sContent, true))) {
                    echo "<tr><td class='narrow-label'>结果集合解析:</td><td><pre>" . var_export($aResult, true) .
                        "</pre></td></tr>";
                }
            }
        }
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            echo "<tr><td class='narrow-label'>返回出错:</td><td><pre>" . $aStatus["http_code"] .
                ",请检查参数或者确实是腾讯服务器出错咯。</pre></td></tr>";
            return false;
        }
    }

    function download($sUrl, $sFileName)
    {
        $oCurl = curl_init();
        $debug = $this->debug;
        set_time_limit(0);
        $oCurl = curl_init();
        if (stripos($sUrl, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($oCurl, CURLOPT_USERAGENT, $_SERVER["USER_AGENT"] ? $_SERVER["USER_AGENT"] :
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.7) Gecko/20100625 Firefox/3.6.7");
        curl_setopt($oCurl, CURLOPT_URL, $sUrl);
        curl_setopt($oCurl, CURLOPT_REFERER, $sUrl);
        curl_setopt($oCurl, CURLOPT_AUTOREFERER, true);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        file_put_contents($sFileName, $sContent);
        if (intval($debug) === 1) {
            echo "<tr><td class='narrow-label'>请求地址:</td><td><pre>" . $sUrl .
                "</pre></td></tr>";
            echo "<tr><td class='narrow-label'>请求信息:</td><td><pre>" . var_export($aStatus, true) .
                "</pre></td></tr>";
        }
        return (intval($aStatus["http_code"]) == 200);
    }

}
